package com.sooth.micro.entity.service;

import cn.hutool.core.collection.CollUtil;
import com.dream.boot.impl.ServiceImpl;
import com.sooth.micro.entity.view.MicroEntityBo;
import com.sooth.micro.entity.view.MicroEntityVo;
import com.sooth.micro.field.service.IMicroFieldService;
import com.sooth.micro.field.view.MicroFieldBo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 实体
 * @Author: moxa
 * @Date: 2023-11-30 19:17:01
 */
@RequiredArgsConstructor
@Service
public class MicroEntityServiceImpl extends ServiceImpl<MicroEntityVo, MicroEntityBo> implements IMicroEntityService {
    private final IMicroFieldService fieldService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(MicroEntityBo microEntity) {
        super.insertFetchKey(microEntity);
        List<MicroFieldBo> fieldList = microEntity.getFieldList();
        if (CollUtil.isNotEmpty(fieldList)) {
            for (MicroFieldBo field : fieldList) {
                field.setEntityId(microEntity.getId());
            }
            fieldService.batchInsert(fieldList);
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(MicroEntityBo microEntity) {
        super.updateById(microEntity);
        fieldService.deleteByEntityId(microEntity.getId());
        List<MicroFieldBo> fieldList = microEntity.getFieldList();
        if (CollUtil.isNotEmpty(fieldList)) {
            fieldService.batchInsert(fieldList);
        }
        return 1;
    }

    @Override
    public MicroEntityBo selectById(Object id) {
        MicroEntityBo microEntity = super.selectById(id);
        List<MicroFieldBo> fieldList = fieldService.selectByEntityId((Long) id);
        microEntity.setFieldList(fieldList);
        return microEntity;
    }

    @Override
    public List<MicroFieldBo> listField(Long id) {
        return fieldService.selectByEntityId(id);
    }

    @Override
    public List<MicroEntityVo> selectVoByIds(List<Long> ids) {
        return templateMapper.selectByIds(MicroEntityVo.class, ids);
    }

    @Override
    public MicroEntityVo selectVoById(Long id) {
        return templateMapper.selectById(MicroEntityVo.class, id);
    }
}
